import { Component, OnInit, Input } from '@angular/core'
import { DValidateRules, FormLayout } from 'ng-devui/form'
import { ToastService } from 'ng-devui'
import { UserAuthService } from 'src/app/@core/user-auth.service'
import { Store } from '@ngrx/store'
import { AppState } from 'src/app/store'
import { Router, ActivatedRoute } from '@angular/router'
import { CookieService } from 'ngx-cookie-service'

@Component({
  selector: 'app-account',
  templateUrl: './account.component.html',
  styleUrls: ['./account.component.scss']
})
export class AccountComponent implements OnInit {
  layoutDirection: FormLayout = FormLayout.Vertical;
  oldPassword: '';
  showOldPassword = false;
  userName: string;
  getUserName: string;

  formRules: { [key: string]: DValidateRules } = {
    rule: { message: '请检查表单!', messageShowType: 'text' },
    passwordRules: {
      validators: [
        { required: true, message: '密码不能为空' },
      ],
    },
  };

  constructor(
    private userAuthService: UserAuthService,
    private router: Router,
    private toastService: ToastService,
    private store: Store<AppState>,
    private activatedRouter: ActivatedRoute,
    private cookieService: CookieService
  ) { }

  ngOnInit(): void {
    this.activatedRouter.queryParams.subscribe(queryParams => {
      this.getUserName = queryParams['userName']
    })
  }

  toastOpen(flag: number, msg: string) {
    if (flag === 0) {
      this.toastService.open({
        value: [{ severity: 'success', summary: '', content: msg }]
      })
      this.cookieService.delete('token')
      localStorage.removeItem('token')
      localStorage.removeItem('userName')
      localStorage.removeItem('ROLE')
      localStorage.removeItem('userId')
      localStorage.removeItem('PasswordChange')
      this.userAuthService.userInfo.userName = null
      this.store.dispatch({
        type: 'RESET_TODO',
        payload: {}
      })
      this.router.navigate(['/login/logins'])
    } else {
      this.toastService.open({
        value: [{ severity: 'error', summary: '', content: msg }]
      })
    }
  }

  submitForm({ valid }) {
    if (valid) {
      if (this.userName == this.getUserName) {
        this.userAuthService
          .accountLogOff(this.oldPassword)
          .subscribe((res) => {
            this.toastOpen(res.code, res.msg)
          })
      } else {
        this.toastService.open({
          value: [
            {
              severity: 'error',
              summary: '',
              content: '输入用户名不正确！'
            }
          ]
        })
      }
    }
  }
}
